package com.sky.JULLog;

//import sun.util.logging.LoggingSupport;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class MySimpleFormatter extends Formatter {

    // format string for printing the log record
//    private static String format = LoggingSupport.getSimpleFormat();
    private   String format  ;

    public MySimpleFormatter() {
        this.setFormat("%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n");
    }

    /**
     * 改成 可以自定义的  格式
     */
    public void setFormat(String format) {
        this.format = format;
    }

    private final Date dat = new Date();


    @Override
    public String getHead(Handler h) {
        return super.getHead(h);
    }

    @Override
    public String getTail(Handler h) {
        return super.getTail(h);
    }

    @Override
    public synchronized String formatMessage(LogRecord record) {
        return super.formatMessage(record);
    }

    /**
     * 父类的 format 方法,  搬来直接修改.....
     * 不管何时何地, 只要上传 class 作为参数给 logger ,  将会输出 类名, 方法名, 行号
     * @param record the log record to be formatted.
     * @return a formatted log record
     */
    @Override
    public synchronized String format(LogRecord record) {
        dat.setTime(record.getMillis());
        String source;
        source = record.getLoggerName();  //mark  其实就是class name
        String fileName = source.substring(source.lastIndexOf('.') +1, source.length());
        for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
            if (element.getClassName().contains(source) && !element.getMethodName().contains("log")){
                source = "[thread:" + Thread.currentThread().getName() +   "]   "  +   source + "."  +element.getMethodName() + "("+  fileName+".java:"+ element.getLineNumber()  +") :    ";
            }
        }
        String message = formatMessage(record);
        String throwable = "";
        if (record.getThrown() != null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            pw.println();
            record.getThrown().printStackTrace(pw);
            pw.close();
            throwable = sw.toString();
        }
        return String.format(format, dat, source, record.getLoggerName(), record.getLevel(), message, throwable);  // mark 不使用 本地化
    }


}
